<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { NButton, NCard, NTabs, NTabPane, NForm, NFormItem, NInput, NInputNumber, NSwitch, NSpace, NAlert, useMessage } from 'naive-ui';
import {
  fetchSystemConfigByType,
  batchUpdateSystemConfig,
  testDorisConnection,
  testDolphinSchedulerConnection,
  refreshConfigCache
} from '@/service/api/dataplatform/system-config';

const message = useMessage();

// 配置类型
const configTypes = [
  { key: 'DORIS', label: 'Doris配置' },
  { key: 'DOLPHINSCHEDULER', label: 'DolphinScheduler配置' },
  { key: 'FLINK', label: 'Flink配置' },
  { key: 'SYSTEM', label: '系统配置' }
];

// 当前选中的配置类型
const activeTab = ref('DORIS');

// 配置数据
const configData = reactive<Record<string, Api.DataPlatform.SystemConfig[]>>({
  DORIS: [],
  DOLPHINSCHEDULER: [],
  FLINK: [],
  SYSTEM: []
});

// 表单数据
const formData = reactive<Record<string, Record<string, any>>>({
  DORIS: {},
  DOLPHINSCHEDULER: {},
  FLINK: {},
  SYSTEM: {}
});

// 加载状态
const loading = ref(false);
const testingConnection = ref(false);

/**
 * 加载配置数据
 */
async function loadConfigData(configType: string) {
  try {
    loading.value = true;
    const { data } = await fetchSystemConfigByType(configType);
    configData[configType] = data || [];
    
    // 初始化表单数据
    formData[configType] = {};
    data?.forEach(config => {
      formData[configType][config.configKey] = config.configValue;
    });
  } catch (error) {
    message.error('加载配置失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 保存配置
 */
async function handleSave() {
  try {
    loading.value = true;
    
    // 构建更新数据
    const updates: Api.DataPlatform.SystemConfigEdit[] = [];
    configData[activeTab.value].forEach(config => {
      const newValue = formData[activeTab.value][config.configKey];
      if (newValue !== config.configValue) {
        updates.push({
          id: config.id,
          configKey: config.configKey,
          configValue: String(newValue),
          configType: config.configType,
          valueType: config.valueType,
          isEncrypted: config.isEncrypted,
          isRequired: config.isRequired
        });
      }
    });
    
    if (updates.length === 0) {
      message.info('没有配置需要更新');
      return;
    }
    
    await batchUpdateSystemConfig(updates);
    message.success('配置保存成功');
    
    // 刷新配置缓存
    await refreshConfigCache();
    
    // 重新加载配置
    await loadConfigData(activeTab.value);
  } catch (error) {
    message.error('配置保存失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 测试连接
 */
async function handleTestConnection() {
  try {
    testingConnection.value = true;
    
    let result;
    if (activeTab.value === 'DORIS') {
      result = await testDorisConnection();
    } else if (activeTab.value === 'DOLPHINSCHEDULER') {
      result = await testDolphinSchedulerConnection();
    } else {
      message.info('该配置类型不支持连接测试');
      return;
    }
    
    if (result.data.success) {
      message.success(result.data.message);
    } else {
      message.error(result.data.message);
    }
  } catch (error) {
    message.error('连接测试失败');
  } finally {
    testingConnection.value = false;
  }
}

/**
 * 标签切换
 */
function handleTabChange(value: string) {
  activeTab.value = value;
  if (configData[value].length === 0) {
    loadConfigData(value);
  }
}

/**
 * 获取输入组件类型
 */
function getInputType(config: Api.DataPlatform.SystemConfig) {
  if (config.valueType === 'NUMBER') {
    return 'number';
  } else if (config.valueType === 'BOOLEAN') {
    return 'switch';
  } else if (config.isEncrypted === 1) {
    return 'password';
  } else {
    return 'text';
  }
}

onMounted(() => {
  loadConfigData(activeTab.value);
});
</script>

<template>
  <div class="system-config-container">
    <NCard title="系统配置" :bordered="false">
      <template #header-extra>
        <NSpace>
          <NButton
            v-if="activeTab === 'DORIS' || activeTab === 'DOLPHINSCHEDULER'"
            type="info"
            :loading="testingConnection"
            @click="handleTestConnection"
          >
            测试连接
          </NButton>
          <NButton type="primary" :loading="loading" @click="handleSave">
            保存配置
          </NButton>
        </NSpace>
      </template>

      <NAlert type="info" :show-icon="true" style="margin-bottom: 16px">
        配置修改后需要保存才能生效，系统会自动刷新配置缓存
      </NAlert>

      <NTabs v-model:value="activeTab" type="line" @update:value="handleTabChange">
        <NTabPane
          v-for="type in configTypes"
          :key="type.key"
          :name="type.key"
          :tab="type.label"
        >
          <NForm
            :model="formData[type.key]"
            label-placement="left"
            label-width="200"
            :show-feedback="false"
          >
            <NFormItem
              v-for="config in configData[type.key]"
              :key="config.id"
              :label="config.description || config.configKey"
              :required="config.isRequired === 1"
            >
              <template v-if="getInputType(config) === 'number'">
                <NInputNumber
                  v-model:value="formData[type.key][config.configKey]"
                  :placeholder="config.defaultValue || '请输入'"
                  style="width: 100%"
                />
              </template>
              <template v-else-if="getInputType(config) === 'switch'">
                <NSwitch
                  v-model:value="formData[type.key][config.configKey]"
                  :checked-value="'true'"
                  :unchecked-value="'false'"
                />
              </template>
              <template v-else-if="getInputType(config) === 'password'">
                <NInput
                  v-model:value="formData[type.key][config.configKey]"
                  type="password"
                  show-password-on="click"
                  :placeholder="config.defaultValue || '请输入'"
                />
              </template>
              <template v-else>
                <NInput
                  v-model:value="formData[type.key][config.configKey]"
                  :placeholder="config.defaultValue || '请输入'"
                />
              </template>
            </NFormItem>
          </NForm>
        </NTabPane>
      </NTabs>
    </NCard>
  </div>
</template>

<style scoped>
.system-config-container {
  padding: 16px;
}
</style>
